package com.zero.insp.services;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @author : pengjie
 * @PackageName : com.zero.insp.services
 * @Description : TODO
 * @email : 627799251@qq.com
 * @Date : 2019/3/26 16:09
 */
@Service
public class UploadService {

    public String tranferFile(MultipartFile multiFile, String flag, String loaclDirPath) throws IOException {
        if (multiFile == null) {
            return "";
        }

        String oriName = multiFile.getOriginalFilename();
        String fileName = flag.toUpperCase() + System.currentTimeMillis() + oriName.substring(oriName.lastIndexOf("."));
        File dirFile = new File(loaclDirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        File file = new File(loaclDirPath + "/" + fileName);
        multiFile.transferTo(file);

        return loaclDirPath + "/" + fileName;
    }

    public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        OutputStream out = response.getOutputStream();
        try {
            byte[] buf = new byte[1024];
            int len = 0;

            response.reset(); //  非常重要
            if (isOnLine) { // 在线打开方式
                URL u = new URL("file:///" + filePath);
                response.setContentType(u.openConnection().getContentType());
                response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
                // 文件名应该编码成UTF-8
            } else { // 纯下载方式
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(f.getName(), "UTF-8"));
            }
            while ((len = br.read(buf)) > 0)
                out.write(buf, 0, len);
        } catch (Exception e) {
        }
        finally {
            br.close();
        }

    }
}
